package com.fb;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import facebook4j.Facebook;
import facebook4j.FacebookFactory;
import facebook4j.Media;
import facebook4j.VideoUpdate;
import facebook4j.auth.AccessToken;
import facebook4j.conf.Configuration;
import facebook4j.conf.ConfigurationBuilder;
import java.io.File;
import java.util.List;

/**
 * @author sad
 */
public class FacebookSender {

    private final String login;
    private final String password;
    private final String appId;
    private final String appSecret;

    public FacebookSender(String login, String password, String appId, String appSecret) {
        this.login = login;
        this.password = password;
        this.appId = appId;
        this.appSecret = appSecret;
    }

    public Configuration createConfiguration() {
        ConfigurationBuilder confBuilder = new ConfigurationBuilder();
        confBuilder.setDebugEnabled(true);
        confBuilder.setOAuthAppId(appId);
        confBuilder.setOAuthAppSecret(appSecret);
        confBuilder.setUseSSL(true);
        confBuilder.setJSONStoreEnabled(true);
        Configuration configuration = confBuilder.build();
        return configuration;
    }

    private String getFacebookAccessToken() throws Exception {
        try {
            final WebClient webClient = new WebClient();
            webClient.setJavaScriptEnabled(false);
            HtmlPage page1 = webClient.getPage("https://www.facebook.com/login/?next=%2F");
            //page1.save(new File("d:/1.html"));
            HtmlForm form = page1.getForms().get(0);

            HtmlTextInput textField = form.getInputByName("email");
            textField.setValueAttribute(login);
            HtmlPasswordInput textField2 = form.getInputByName("pass");
            textField2.setValueAttribute(password);
            HtmlSubmitInput button = (HtmlSubmitInput) form.getInputsByName("login").get(0);
            HtmlPage page2 = button.click();
            System.out.println("Status = " + page2.getWebResponse().getStatusCode());
            HtmlPage developersPage = webClient.getPage("https://developers.facebook.com/tools/accesstoken/");
            String searchString = "https://developers.facebook.com/tools/debug?q=";
            List<HtmlAnchor> value = (List<HtmlAnchor>) developersPage.getByXPath(String.format("//*[contains(@href,'%s')]", searchString));
            String hrefValue = value.get(0).getHrefAttribute();
            return hrefValue.substring(searchString.length());
        } catch (Exception ex) {
            System.err.println("ERROR!!! Cannot upload video to facebook. It seems that facebook login password is wrong");
            ex.printStackTrace();
            return null;
        }
    }

    public String startVideoFileUploading(File file, String destEmail) throws Exception {
        String ts = getFacebookAccessToken();
        if (ts == null) {
            System.out.println("Cannot get facebook access token. Exit.");
            return null;
        }

        Configuration configuration = createConfiguration();
        FacebookFactory facebookFactory = new FacebookFactory(configuration);
        Facebook fb = facebookFactory.getInstance();
        AccessToken token = new AccessToken(ts);
        fb.setOAuthAccessToken(token);
        fb.setOAuthPermissions("publish_actions");
        VideoUpdate vu = new VideoUpdate(new Media(file));
        vu.setDescription("Video saved by "+destEmail);
        String videoId = fb.videos().postVideo(vu);
        String resultUrl = "https://www.facebook.com/photo.php?v=" + videoId;
        System.out.println(resultUrl);
        return resultUrl;
    }
}
